<?php
namespace app\http;
use \Workerman\Lib\Timer;
use think\worker\Server;
use think\Db;
class Worker extends Server
{

    protected $protocol    = 'tcp'; // 协议 支持 tcp udp unix http websocket text
    protected $host       = '0.0.0.0'; // 监听地址
    protected $port     = 2347; // 监听端口

    protected $name = 'thinkphp';
    protected $count      = 1;
	protected $lian=[];
	public function onWorkerStart($worker){
		//这个是定时器示例
		 $time_interval = 5;
		 Timer::add($time_interval, function()
		 {
		 	//上传到七牛云
		 	$wo=Db::name('book_show')->where('is_qiniu',0)->limit(3)->column('mp3');
		 	foreach($wo as $data){
		 		$uploadMgr = new \Qiniu\Storage\UploadManager();
		 		$auth = new \Qiniu\Auth(config('qiniu')['accessKey'],config('qiniu')['secretKey']);
		 		$token = $auth->uploadToken(config('qiniu')['bucket']);
		 		
		 		//查询是否存在
		 		$config = new \Qiniu\Config();
		 		$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
		 		list($fileInfo, $err) = $bucketManager->stat(config('qiniu')['bucket'], substr($data,1));
		 		if ($err) {
		 			//如果不存在，在上传
		 			list($ret, $error) = $uploadMgr->putFile($token,substr($data,1) , env('root_path').'public/'.substr($data,1));
		 			if(!$error){
		 				 Db::name('book_show')->where('mp3',$data)->update(['is_qiniu'=>1]);
		 			}
		 		} else {
		 			print_r($fileInfo);
		 		}
		 		//查询结束
		 	}
		 });
	}
	public function onConnect($connection)
	{
		//dump($connection);
	}
	public function onMessage($connection,$data)
	{
		$connection->send('99');
		dump($data);
	}
	public function onClose($connection)
	{
		
	}
	public function onError($connection, $code, $msg) 
	{
        echo "error [ $code ] $msg\n";
    }
}

